package agi

import (
	"os"
	"os/exec"
	"path/filepath"
	"io/ioutil"
	"bytes"
	"time"
)

func SplitDirFile(path string) (string, string) {
	return filepath.Dir(path), filepath.Base(path)
}

func RealPathSplitDirFile(path string) (string, string, error) {
	p, err := exec.LookPath(path)
	dir := GetOsDirSpr()
	file := ""
	if err != nil {
		return dir, file, err
	}
	return filepath.Dir(p), filepath.Base(p), nil
}

func Exist(path string) bool {
	_, err := os.Stat(path)
	return err != nil
}

func IsFile(path string) bool {
	stat, err := os.Stat(path)
	if err == nil {
		return !stat.IsDir()
	}
	return false
}

func IsDir(path string) bool {
	stat, err := os.Stat(path)
	if err == nil {
		return stat.IsDir()
	}
	return false
}

func ReadFileByte(path string) ([]byte, error) {
	fi, err := os.Open(path)
	if err != nil {
		//		panic(err)
		return nil, err
	} else {
		defer fi.Close()
		return ioutil.ReadAll(fi)
	}
}

func ReadFileStr(path string) (string, error) {
	raw, err := ReadFileByte(path)
	return string(raw), err
}

// Golang的时间格式真让人无力吐槽了
// 没加全，起码够用，以后再补
func TF(format string) (string) {
	// Mon Jan 2 15:04:05 -0700 MST 2006
	oldBytes := []byte(format)
	newBytes := bytes.NewBuffer([]byte{})
	for i, l := 0, len(oldBytes); i < l; i++ {
		b := oldBytes[i]
		switch b {
			case 89 : // Y
			newBytes.WriteString("2006")
			case 121: // y
			newBytes.WriteString("06")
			case 109 : // m
			newBytes.WriteString("01")
			case 110 : // n
			newBytes.WriteString("1")
			case 100 : // d
			newBytes.WriteString("02")
			case 106 : // j
			newBytes.WriteString("2")
			//            case 71 : // G
			//            newBytes.WriteString("3")
			case 72 : // H
			newBytes.WriteString("15")
			case 105 : // i
			newBytes.WriteString("04")
			case 115 : // s
			newBytes.WriteString("05")
			default :
			newBytes.WriteByte(b)
		}
		//        fmt.Println(oldBytes[i])
	}
	return newBytes.String()
}

func OffsetIndex(index int, size int) int {
	if index < 0 || index >= size {
		if index < 0 {
			index = size + index % size
			if index == size {
				index = 0
			}
		} else {
			index = (index - size) % size
		}
	}
	return index
}


func Seconds(seconds int) time.Duration {
	return time.Duration(seconds) * time.Second
}

func Minutes(minutes int) time.Duration {
	return time.Duration(minutes) * time.Minute
}

func Hours(hours int) time.Duration {
	return time.Duration(hours) * time.Hour
}
